package tech.$2306.comment.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tech.$2306.comment.model.dto.IPAddressDTO;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Wangls
 * @since 2021-04-10 01:21
 * 用于解析IP地址的所在位置及ISP信息
 */
@Component
@Slf4j
public class IPAddressUtil {

    @Value("${baiduIPApi.url}")
    private String apiUrl;

    @Value("${baiduIPApi.AccessKey}")
    private String accessKey;

    @Value("${baiduIPApi.AppSecret}")
    private String secretKey;

    public IPAddressDTO resolveIPAddress(String ipString) {
        IPAddressDTO ipAddressDTO = null;

        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, apiUrl);
        request.setCredentials(accessKey, secretKey);

        // 设置header参数
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");

        Map<String, String> paramMap = Maps.newHashMap();
        paramMap.put("ip",ipString);
        request.setJsonBody(JSON.toJSONString(paramMap));

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            log.info("{}",response.getResult());
            ipAddressDTO = JSONObject.parseObject(response.getResult(), IPAddressDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ipAddressDTO;
    }


    public String getIPAddress(HttpServletRequest request) {
        String ip=request.getHeader("x-forwarded-for");
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
            ip=request.getHeader("Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
            ip=request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
                        ip=request.getRemoteAddr();
        }
        return ip;
    }

}
